//
//  ViewController.swift
//  VideoClip
//
//  Created by delouch on 2024/10/6.
//

import Cocoa
import AVFoundation
import Foundation

class ViewController: NSViewController {

    lazy var queue: OperationQueue = {
        let q = OperationQueue()
        q.maxConcurrentOperationCount = 3
        return q
    }()
    
    lazy var clipBtn: NSButton = {
        let btn = NSButton(title: "begin", target: self, action: #selector(clipFunc))
        btn.contentTintColor = NSColor.black
        btn.font = NSFont.systemFont(ofSize: 15)
        self.view.addSubview(btn)
        return btn
    }()
        
    override func viewDidLoad() {
        super.viewDidLoad()
        clipBtn.frame = self.view.bounds
    }
    
    @objc func clipFunc() {

        var fileList : [FileInfo] = []
        FilesEnum.enumerateFiles(at: "/Users/delouch/Movies/clip", list: &fileList)
        
        var finishCount : Int = 0
        
        clipBtn.title = "\(finishCount)/\(fileList.count)";
        
        if fileList.count > 0 {
            clipBtn.isEnabled = false
        }
                
        for file in fileList {
            
            let operation = ClipOperation(file: file)
            operation.completionBlock = {[weak self]in
                finishCount += 1;
                DispatchQueue.main.async {
                    self?.clipBtn.isEnabled = (finishCount == fileList.count) ? true : false
                    if self?.clipBtn.isEnabled ?? false == true {
                        self?.clipBtn.title = "begin"
                    }else {
                        self?.clipBtn.title = "\(finishCount)/\(fileList.count)";
                    }
                }
            }
            self.queue.addOperation(operation)
            
        }
    }

}
